import java.nio.ByteBuffer;

/**
 * 报文Frame
 *
 * @author loafer
 */
public class Pack extends BaseInformationElement {

    /**
     * 启动符的魔数
     */
    private final static byte MAGIC_NUMBER = 0x02;

    private final static byte MAGIC_NUMBER_END = 0x03;

    /**
     * 因为java 中没有无符号整形 所以用 int 表示
     */
    private final int len;

    private final short path;

    private static byte type;
    private final Long id;

    private BaseInformationElement count;
    private final byte ext;
    private byte lrc;

    /**
     * 解码构造方法
     *
     * @param byteBuffer
     */
    public Pack(ByteBuffer byteBuffer) {
        super(byteBuffer);
        int magicNumber = byteBuffer.get();

        if (magicNumber != MAGIC_NUMBER) {
            throw new RuntimeException("魔数校验头错误");
        }
        len = byteBuffer.getShort();
        path = byteBuffer.get();
        type = byteBuffer.get();
        id = byteBuffer.getLong();
        // 用反射工厂来 调用
        DataFactory.deserialize(DataFactory.getClass(type), byteBuffer);
        //
        ext = byteBuffer.get();
        lrc = byteBuffer.get();
    }

    @Override
    public void encode(ByteBuffer byteBuf) {
        byteBuf.put(MAGIC_NUMBER);
        //报文长度 无符号整形
        byteBuf.put((byte) count.getLen());
        byteBuf.putShort(path);
        byteBuf.putLong(id);
        byteBuf.put(type);
        count.encode(byteBuf);
        byteBuf.put(MAGIC_NUMBER_END);
        // lcr 算法我看不到 ...Factory
        byteBuf.put(lrc);
    }

    @Override
    public int getLen() {
        return count.getLen();
    }
}
